<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="盘点编号" prop="chkTaskNo">
        <el-input v-model="queryParams.chkTaskNo" placeholder="请输入盘点编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="任务状态" prop="statusCode">
        <el-select v-model="queryParams.statusCode" placeholder="请选择任务状态" clearable>
          <el-option v-for="dict in dict.type.it_status_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资产大类" prop="assetsCategory">
        <el-select v-model="queryParams.assetsCategory" placeholder="请选择资产大类" clearable>
          <el-option v-for="dict in dict.type.md_assets_category" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务时间">
        <el-date-picker v-model="dateRange1" type="datetimerange" :picker-options="pickerOptions" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="盘点时间">
        <el-date-picker v-model="dateRange2" type="datetimerange" :picker-options="pickerOptions" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['meter:checkTask:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-switch-button" size="mini" @click="countingStartBtn" v-hasPermi="['meter:checkTask:startCheck']">盘点开始</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-switch-button" size="mini" @click="countingEndBtn" v-hasPermi="['meter:checkTask:endCheck']">盘点完成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['meter:checkTask:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['meter:checkTask:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkTaskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务单标识" align="center" prop="chkTaskId" min-width="110px" />
      <el-table-column label="盘点单号" align="center" prop="chkTaskNo" width="220px" />
      <el-table-column label="资产大类" align="center" prop="assetsCategory">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.md_assets_category" :value="scope.row.assetsCategory" />
        </template>
      </el-table-column>
      <el-table-column label="盘点范围" align="center" prop="checkRange">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.check_range" :value="scope.row.checkRange" />
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="statusCode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.it_status_code" :value="scope.row.statusCode" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="库房" align="center" prop="whName" min-width="340px" />
      <el-table-column label="库区标识" align="center" prop="whAreaId" v-if="false" />
      <el-table-column label="库区" align="center" prop="whAreaname" min-width="130px" />
      <el-table-column label="存放区标识" align="center" prop="storeAreaId" v-if="false" />
      <el-table-column label="存放区" align="center" prop="storeAreaName" min-width="110px" />
      <el-table-column label="储位标识" align="center" prop="storeLocId" v-if="false" />
      <el-table-column label="储位" align="center" prop="storeLocName" min-width="120px" /> -->
      <el-table-column label="盘点人" align="center" prop="nickName" min-width="100px" />
      <el-table-column label="盘点时间" align="center" prop="chkDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.chkDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="任务时间" align="center" prop="taskDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" min-width="350px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="viewDetails(scope.row)" v-hasPermi="['meter:mdChkTaskDetails:list']">查看详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-document" @click="processingDetails(scope.row)" v-hasPermi="['meter:mdChkTaskDetails:edit']">处理明细</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleExport(scope.row)" v-hasPermi="['meter:checkTask:export']">导出</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['meter:checkTask:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['meter:checkTask:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改盘点任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" v-if="title == '添加盘点任务'">
        <!-- <el-form-item label="盘点人" prop="chkUserId">
          <el-select v-model="form.chkUserId" placeholder="请选择盘点人">
            <el-option v-for="item in userList" :key="item.deptId" :label="item.nickName" :value="item.userId"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="盘点编号" prop="chkTaskNo">
          <el-input v-model="form.chkTaskNo" placeholder="自动生成" maxlength="50" readonly :disabled="true" />
        </el-form-item>

        <el-form-item label="资产大类" prop="assetsCategory">
          <el-select v-model="form.assetsCategory" placeholder="请选择资产大类" clearable>
            <el-option v-for="dict in dict.type.md_assets_category" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盘点范围" prop="checkRange">
          <el-select v-model="form.checkRange" placeholder="请选择盘点范围" clearable>
            <el-option v-for="dict in dict.type.check_range" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="库房" prop="whId">
          <el-select v-model="form.whId" placeholder="请选择库房" @change="changeWhId">
            <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区" prop="whAreaId">
          <el-select v-model="form.whAreaId" placeholder="请选择库区" @change="changeWhAreaId">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存放区" prop="storeAreaId">
          <el-select v-model="form.storeAreaId" placeholder="请选择存放区" @change="changeStoreAreaId">
            <el-option v-for="item in optionss" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="储位" prop="storeLocId">
          <el-select v-model="form.storeLocId" placeholder="请选择储位">
            <el-option v-for="item in storageOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务时间" prop="taskDate">
          <el-date-picker clearable v-model="form.taskDate" type="datetime" value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="请选择任务时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <el-form ref="forms" :model="forms" :rules="rules" label-width="80px" v-if="title == '修改盘点任务'">
        <!-- <el-form-item label="盘点人" prop="chkUserId">
          <el-select v-model="forms.chkUserId" placeholder="请选择盘点人">
            <el-option v-for="item in userList" :key="item.deptId" :label="item.nickName" :value="item.userId"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="资产大类" prop="assetsCategory">
          <el-select v-model="forms.assetsCategory" placeholder="请选择资产大类" clearable>
            <el-option v-for="dict in dict.type.md_assets_category" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="盘点范围" prop="checkRange">
          <el-select v-model="forms.checkRange" placeholder="请选择盘点范围" clearable>
            <el-option v-for="dict in dict.type.check_range" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="库房" prop="whId">
          <el-select v-model="forms.whId" placeholder="请选择库房" @change="changeWhId">
            <el-option v-for="item in option" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库区" prop="whAreaId">
          <el-select v-model="forms.whAreaId" placeholder="请选择库区" @change="changeWhAreaId">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="存放区" prop="storeAreaId">
          <el-select v-model="forms.storeAreaId" placeholder="请选择存放区" @change="changeStoreAreaId">
            <el-option v-for="item in optionss" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="储位" prop="storeLocId">
          <el-select v-model="forms.storeLocId" placeholder="请选择储位">
            <el-option v-for="item in storageOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务时间" prop="taskDate">
          <el-date-picker clearable v-model="forms.taskDate" type="datetime" value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="请选择任务时间">
          </el-date-picker>
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="forms.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="detailsTitle" :visible.sync="detailsOpen" width="1200px" v-if="detailsTitle == '盘点任务详情'">
      <el-table v-loading="loading" :data="checkTaskDetails" border>
        <el-table-column label="盘点任务详情标识" align="center" prop="taskDetailsId" min-width="100px" />
        <!-- <el-table-column label="盘点任务标识" align="center" prop="chkTaskId" /> -->
        <el-table-column label="条形码" align="center" prop="rfidNo" min-width="200px" />
        <el-table-column label="设备码" align="center" prop="equipCode" min-width="220px" />
        <el-table-column label="设备名称" align="center" prop="equipName" min-width="550px" />
        <el-table-column label="盘点结果" align="center" prop="chkResult">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.ctr_chk_result" :value="scope.row.chkResult" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>
      <pagination v-show="num > 0" :total="num" :page.sync="queryParamss.pageNum" :limit.sync="queryParamss.pageSize"
        @pagination="viewDetailsPage" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">返 回</el-button>
      </div>
    </el-dialog>

    <!--处理明细-->
    <el-dialog :title="processingText" :visible.sync="processing" width="1200px" v-if="detailsTitle == '处理明细'">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-upload2" size="mini" @click="chkNormal">盘点正常</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="checkTaskDetails" border @selection-change="handleSelectionChangeDetail">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="盘点任务详情标识" align="center" prop="taskDetailsId" min-width="100px" />
        <!-- <el-table-column label="盘点任务标识" align="center" prop="chkTaskId" /> -->
        <el-table-column label="盘点结果" align="center" prop="chkResult">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.ctr_chk_result" :value="scope.row.chkResult" />
          </template>
        </el-table-column>
        <el-table-column label="条形码" align="center" prop="rfidNo" min-width="200px" />
        <el-table-column label="设备码" align="center" prop="equipCode" min-width="220px" />
        <el-table-column label="设备名称" align="center" prop="equipName" min-width="550px" />
        <el-table-column label="盘点结果" align="center" prop="chkResult">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.ctr_chk_result" :value="scope.row.chkResult" />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>
      <pagination v-show="num > 0" :total="num" :page.sync="queryParamss.pageNum" :limit.sync="queryParamss.pageSize"
        @pagination="viewDetailsPage" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDetail">返 回</el-button>
      </div>
    </el-dialog>

    <!-- 导入对话框 -->
    <!-- <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
                  <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
                </div> -->
    <!-- <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>
  import {
    listCheckTask,
    getCheckTask,
    delCheckTask,
    addCheckTask,
    updateCheckTask,
    queryCheckTaskDetails,
    countingStart,
    countingEnd,
    checkTaskNormal
  } from "@/api/meter/checkTask";
  import {
    selectMdWhInfo,
    selectMdStorageAreaInfo,
    selectMdSaInfo,
    selectStorageLocation
  } from "@/api/meter/mdWhInfo";
  import {
    listUser
  } from "@/api/system/user"
  import {
    getToken
  } from "@/utils/auth";
  import {
    jsonMdChkTask
  } from "@/api/meter/downloadData"

  export default {
    name: "CheckTask",
    dicts: ["md_assets_category", "it_status_code", "ctr_chk_result", "check_range"],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 选中数组明细
        idDetails: [],
        // 日期范围
        dateRange1: [],
        dateRange2: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        //添加任务明细选中数组--处理明细
        detailsSelection: [],
        // 总条数
        total: 0,
        // 盘点任务表格数据
        checkTaskList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        //是否显示处理明细弹出层
        processing: false,
        //处理明细层标题
        processingText: "",
        // 数据导入参数
        upload: {
          // 是否显示弹出层
          open: false,
          // 弹出层标题
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          // updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: "Bearer " + getToken()
          },
          // 上传的地址
          // url: process.env.VUE_APP_BASE_API + "/system/user/importData"
        },
        //处理明细查询参数
        inquireAbout: {},
        //处理明细资产大类
        cateGory: "",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          statusCode: null,
          assetsCategory: null
        },
        //查看详情查询参数
        queryParamss: {
          pageNum: 1,
          pageSize: 10,
          chkTaskId: null
        },
        //查看详情主键
        queryChkTaskId: null,
        // 表单参数
        form: {},
        forms: {},
        // 表单校验
        rules: {
          assetsCategory: [{
            required: true,
            message: '请选择资产大类',
            trigger: 'change'
          }],
          checkRange: [{
            required: true,
            message: '请选择盘点范围',
            trigger: 'change'
          }],
          // chkUserId: [{
          //   required: true,
          //   message: '请选择盘点人',
          //   trigger: 'change'
          // }],
        },
        //库房下拉框
        option: [],
        //库区下拉框
        options: [],
        //存放区下拉框
        optionss: [],
        //储位下拉框
        storageOption: [],
        //盘点详情数据
        checkTaskDetails: [],
        //盘点详情条数
        num: 0,
        //盘点详情标题
        detailsTitle: '',
        //盘点详情页面是否打开
        detailsOpen: false,
        //盘点人列表
        userList: [],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询盘点任务列表 */
      getList() {
        this.loading = true;
        listCheckTask(this.addDateRanges(this.queryParams, this.dateRange1, this.dateRange2)).then(response => {
          this.checkTaskList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        const dateRange = []
        const queryParam = {
          pageNum: 1,
          pageSize: 10
        }
        listUser(queryParam, dateRange).then(response => {
          this.userList = response.rows
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.detailsOpen = false;
        this.reset();
      },
      // 取消按钮
      cancelDetail() {
        this.processing = false;
        this.reset();
      },

      // 表单重置
      reset() {
        this.form = {
          chkTaskId: null,
          whId: null,
          whAreaId: null,
          storeAreaId: null,
          storeLocId: null,
          chkUserId: null,
          chkDate: null,
          statusCode: null,
          taskDate: null,
          remark: null,
          assetsCategory: null,
          checkRange: null
        };
        this.forms = {
          chkTaskNo: null,
          chkTaskId: null,
          whId: null,
          whAreaId: null,
          storeAreaId: null,
          storeLocId: null,
          chkUserId: null,
          chkDate: null,
          statusCode: null,
          taskDate: null,
          remark: null,
          assetsCategory: null,
          checkRange: null
        };
        this.resetForm("form");
        this.resetForm("forms");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange1 = [];
        this.dateRange2 = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.chkTaskId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      // 多选框选中数据
      handleSelectionChangeDetail(selection) {
        this.idDetails = selection.map(item => item.taskDetailsId)
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        selectMdWhInfo().then(response => {
          this.option = response.data
          this.form.whId = this.option[0].value
          this.changeWhId()
          setTimeout(() => {
            this.open = true;
            this.title = "添加盘点任务";
          }, 200);
        })
      },
      /** 盘点开始按钮 */
      countingStartBtn(row) {
        const chkTaskIds = this.ids
        if (chkTaskIds == "") {
          this.$message.error('至少选择一条盘点单');
        }
        if (chkTaskIds.length == 1) {
          this.checkTaskList.forEach(item => {
            if (item.chkTaskId == chkTaskIds) {
              if (item.statusCode == '02') {
                this.$message.error('盘点已经开始，请勿重复点击');
                this.getList()
              } else {
                countingStart(chkTaskIds).then(response => {
                  this.$message({
                    message: '盘点开始',
                    type: 'success'
                  });
                  this.getList()
                })
              }
            }
          });
        } else {
          for (let i = 0; i < chkTaskIds.length; i++) {
            this.checkTaskList.forEach(item => {
              if (item.chkTaskId == chkTaskIds[i]) {
                if (item.statusCode == '02') {
                  this.$message.error(`任务单为${chkTaskIds[i]}的数据盘点已经开始，请勿重复点击`);
                  this.getList()
                } else {
                  countingStart(chkTaskIds).then(response => {
                    this.$message({
                      message: '盘点开始',
                      type: 'success'
                    });
                    this.getList()
                  })
                }
              }
            })
          }
        }
      },

      /** 盘点开始按钮 */
      countingEndBtn(row) {
        const chkTaskIds = this.ids
        if (chkTaskIds == "") {
          this.$message.error('至少选择一条盘点单');
        }
        if (chkTaskIds.length == 1) {
          this.checkTaskList.forEach(item => {
            if (item.chkTaskId == chkTaskIds) {
              if (item.statusCode == '03') {
                this.$message.error('盘点已经结束，请勿重复点击');
                this.getList()
              } else {
                countingEnd(chkTaskIds).then(response => {
                  this.$message({
                    message: '盘点结束',
                    type: 'success'
                  });
                  this.getList()
                })
              }
            }
          });
        } else {
          for (let i = 0; i < chkTaskIds.length; i++) {
            this.checkTaskList.forEach(item => {
              if (item.chkTaskId == chkTaskIds[i]) {
                if (item.statusCode == '03') {
                  this.$message.error(`任务单为${chkTaskIds[i]}的数据盘点已经结束，请勿重复点击`);
                  this.getList()
                } else {
                  countingEnd(chkTaskIds).then(response => {
                    this.$message({
                      message: '盘点结束',
                      type: 'success'
                    });
                    this.getList()
                  })
                }
              }
            })
          }
        }
      },

      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const chkTaskId = row.chkTaskId || this.ids
        getCheckTask(chkTaskId).then(response => {
          this.forms = response.data;
          selectMdWhInfo().then(response => {
            this.option = response.data
            this.changeWhId()
            this.changeQurey()
            this.changeQueryStoreAreaId()
            setTimeout(() => {
              this.open = true;
              this.title = "修改盘点任务";
            }, 200);
          })
        });
      },
      /** 查看详情按钮 */
      viewDetails(row) {
        this.queryChkTaskId = row.chkTaskId || this.ids
        this.queryParamss.chkTaskId = this.queryChkTaskId
        queryCheckTaskDetails(this.queryParamss).then(response => {
          this.checkTaskDetails = response.rows
          this.num = response.total
          this.detailsOpen = true
          this.loading = false;
          this.detailsTitle = "盘点任务详情"
        })
      },
      //查看详情分页
      viewDetailsPage() {
        this.queryParamss.chkTaskId = this.queryChkTaskId
        queryCheckTaskDetails(this.queryParamss).then(response => {
          this.checkTaskDetails = response.rows
          this.num = response.total
          this.detailsOpen = true
          this.loading = false;
          this.detailsTitle = "盘点任务详情"
        })
      },
      /** 提交按钮 */
      submitForm() {
        if (this.title == "修改盘点任务") {
          this.$refs["forms"].validate(valid => {
            if (valid) {
              updateCheckTask(this.forms).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            }
          })
        } else {
          this.$refs["form"].validate(valid => {
            if (valid) {
              addCheckTask(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          })
        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const chkTaskIds = row.chkTaskId || this.ids;
        this.$modal.confirm('是否确认删除盘点任务编号为"' + chkTaskIds + '"的数据项？').then(function() {
          return delCheckTask(chkTaskIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport(row) {
        const chkTaskId = row.chkTaskId
        this.download('meter/mdChkTaskDetails/export', {
          chkTaskId
        }, `盘点详情明细${chkTaskId}.xlsx`)
      },


      //处理明细按钮
      processingDetails(row) {
        if (row.statusCode == '03') {
          this.$message.error('盘点已经结束，无法处理！');
          this.getList()
        }
        this.queryChkTaskId = row.chkTaskId || this.ids
        console.log(this.queryChkTaskId)
        this.queryParamss.chkTaskId = this.queryChkTaskId
        queryCheckTaskDetails(this.queryParamss).then(response => {
          this.checkTaskDetails = response.rows
          this.num = response.total
          this.detailsOpen = true
          this.detailsTitle = "处理明细"
          this.processing = true;
          this.processingText = "处理明细"
        })
      },

      //处理明细提交
      chkNormal(row) {
        this.reset();
        const taskId = this.queryChkTaskId;
        const taskDetailsIds = row.taskDetailsId || this.idDetails;
        this.$modal.confirm('是否提交编号为"' + taskDetailsIds + '"的数据项为盘点正常？').then(function() {
          return checkTaskNormal(taskDetailsIds, taskId);
        }).then(() => {
          // this.getList();
          this.$modal.msgSuccess("提交成功");
          this.processing = false;
        }).catch(() => {});
      },


      //库房下拉框改变事件
      changeWhId() {
        let queryParams = {}
        queryParams.whId = this.form.whId || this.forms.whId
        selectMdStorageAreaInfo(queryParams).then(response => {
          this.options = response.data
        })
      },
      //库区下拉框改变事件
      changeWhAreaId() {
        //定义请求查询参数
        let queryParams = {}
        //对查询参数进行赋值
        queryParams.whId = this.form.whId || this.forms.whId
        queryParams.whAreaId = this.form.whAreaId || this.forms.whAreaId
        //改变的时候，将存放区以及储位设置为空
        this.form.storeAreaId = null;
        this.forms.storeAreaId = null;
        this.form.storeLocId = null;
        this.forms.storeLocId = null;
        this.storageOption = []
        //进行请求
        selectMdSaInfo(queryParams).then(response => {
          this.optionss = response.data
        })
      },
      //存放区下拉框改变事件
      changeStoreAreaId() {
        let queryParams = {}
        queryParams.whId = this.form.whId || this.forms.whId
        queryParams.whAreaId = this.form.whAreaId || this.forms.whAreaId
        queryParams.storeAreaId = this.form.storeAreaId || this.forms.storeAreaId
        this.form.storeLocId = null;
        this.forms.storeLocId = null;
        selectStorageLocation(queryParams).then(response => {
          this.storageOption = response.data
        })
      },
      //修改时调用查询库区下拉框数据事件
      changeQurey() {
        let queryParams = {}
        //对查询参数进行赋值
        queryParams.whId = this.form.whId || this.forms.whId
        queryParams.whAreaId = this.form.whAreaId || this.forms.whAreaId
        selectMdSaInfo(queryParams).then(response => {
          this.optionss = response.data
        })
      },
      //修改时调用查询存放区下拉框数据事件
      changeQueryStoreAreaId() {
        let queryParams = {}
        queryParams.whId = this.form.whId || this.forms.whId
        queryParams.whAreaId = this.form.whAreaId || this.forms.whAreaId
        queryParams.storeAreaId = this.form.storeAreaId || this.forms.storeAreaId
        selectStorageLocation(queryParams).then(response => {
          this.storageOption = response.data
        })
      },
      // /** 导入按钮操作 */
      // handleImport() {
      //   this.upload.title = "数据导入";
      //   this.upload.open = true;
      // },
      // /** 下载模板操作 */
      // importTemplate() {
      //   // this.download('system/user/importTemplate', {
      //   // }, `user_template_${new Date().getTime()}.xlsx`)
      // },
      // // 文件上传中处理
      // handleFileUploadProgress(event, file, fileList) {
      //   this.upload.isUploading = true;
      // },
      // // 文件上传成功处理
      // handleFileSuccess(response, file, fileList) {
      //   this.upload.open = false;
      //   this.upload.isUploading = false;
      //   this.$refs.upload.clearFiles();
      //   this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      //   this.getList();
      // },
      // // 提交上传文件
      // submitFileForm() {
      //   // this.$refs.upload.submit();
      // },
      //下载数据按钮
      downloadData() {
        if (this.ids.length == 0) {
          let array = [];
          this.checkTaskList.forEach(item => {
            if (item.statusCode == '02') {
              array.push(item.chkTaskId)
            }
          })
          let queryParams = {
            chkTaskIds: array
          }
          if (array != "") {
            this.$confirm('此操作将下载所有文件, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              jsonMdChkTask(queryParams).then(response => {
                if (response.code == 200) {
                  this.$message({
                    message: `数据成功下载至${response.msg}中`,
                    type: 'success'
                  });
                } else {
                  this.$message.error('数据下载失败');
                }
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消下载'
              });
            });
          } else {
            this.$message.error('当前页面数据全未为开始盘点状态');
          }
          // this.$confirm('此操作将下载所有文件, 是否继续?', '提示', {
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // }).then(() => {
          //   jsonMdChkTask(queryParams).then(response => {
          //     if (response.code == 200) {
          //       this.$message({
          //         message: `数据成功下载至${response.msg}中`,
          //         type: 'success'
          //       });
          //     } else {
          //       this.$message.error('数据下载失败');
          //     }
          //   })
          // }).catch(() => {
          //   this.$message({
          //     type: 'info',
          //     message: '已取消下载'
          //   });
          // });
        } else {
          let queryParams = {
            chkTaskIds: JSON.parse(JSON.stringify(this.ids))
          }
          const chkTaskId = this.ids
          for (let i = 0; i < chkTaskId.length; i++) {
            this.checkTaskList.forEach(item => {
              if (item.chkTaskId == chkTaskId[i]) {
                if (item.statusCode != '02') {
                  this.$message.error(`单据${chkTaskId[i]}不是开始盘点状态，请重新选择!`);
                } else {
                  jsonMdChkTask(queryParams).then(response => {
                    if (response.code == 200) {
                      this.$message({
                        message: `数据成功下载至${response.msg}中`,
                        type: 'success'
                      });
                    } else {
                      this.$message.error('数据下载失败');
                    }
                  })
                }
              }
            })
          }
        }
      }
    }
  };
</script>
